def binary_search(nums, target):
    """
    写法1：查找范围含right
    """
    left = 0
    right = len(nums)

    while left <= right:
        mid = (left + right) // 2
        if nums[mid] > target:
            right = mid - 1
        elif nums[mid] < target:
            left = mid + 1
        else:
            return mid


def binary_search2(nums, target):
    # 写法2：查找范围不含right
    left = 0
    right = len(nums) + 1
    while left < right:
        mid = (left + right) // 2
        if nums[mid] > target:
            right = mid
        elif nums[mid] < target:
            left = mid + 1
        else:
            return mid


if __name__ == '__main__':
    nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    print(binary_search(nums, 5))
    print(binary_search2(nums, 5))
